package com.project.capture5.app;

import com.project.capture5.bean.MarketingUserBehavior;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * @author Shelly An
 * @create 2020/9/18 16:33
 * 不同渠道不同行为的统计
 */
public class AppMarketingAnalysis {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //1. 读取数据
        DataStreamSource<MarketingUserBehavior> appDS = env.addSource(new SourceFunction<MarketingUserBehavior>() {

            private boolean flag = true;
            private List<String> behaviorList = Arrays.asList("DOWNLOAD", "INSTALL", "UPDATE", "UNINSTALL");
            private List<String> channelList = Arrays.asList("XIAOMI", "HUAWEI", "OPPO", "VIVO");


            @Override
            public void run(SourceContext<MarketingUserBehavior> ctx) throws Exception {
                while (flag) {
                    Random random = new Random();
                    //Long userId, String behavior, String channel, Long timestamp
                    ctx.collect(new MarketingUserBehavior(
                            (long) random.nextInt(10),
                            behaviorList.get(random.nextInt(behaviorList.size())),
                            channelList.get(random.nextInt(channelList.size())),
                            System.currentTimeMillis()
                    ));
                    Thread.sleep(1000L);
                }
            }

            @Override
            public void cancel() {
                this.flag = false;
            }
        });

        //2. 处理数据 不同渠道不同行为的统计
        //2.1 按照统计的维度分组，渠道，行为多个维度可以拼接在一起 转换成 (渠道_行为,1)二元组
        SingleOutputStreamOperator<Tuple2<String, Integer>> channelBehaviorDS = appDS.map(new MapFunction<MarketingUserBehavior, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(MarketingUserBehavior value) throws Exception {
                return Tuple2.of(value.getChannel() + "_" + value.getBehavior(), 1);
            }
        });

        //2.2 按照 渠道_行为 分组
        KeyedStream<Tuple2<String, Integer>, String> channelBehaviorKS = channelBehaviorDS.keyBy(data -> data.f0);

        //2.3 求和
        SingleOutputStreamOperator<Tuple2<String, Integer>> resultDS = channelBehaviorKS.sum(1);

        //2.4 输出
        resultDS.print("app marketing analysis by channel and behavior");

        env.execute();
    }
}
